﻿@using TD.Common.Kendo.Mvc5.Grid

@model TD.CTS.Data.Entities.Trial

@Html.Partial("EditorTemplates/TrialVersionEditor", Model)

@(Html.Kendo().Grid<TD.CTS.Data.Entities.TrialProcedure>()
    .Name("ProcedureRolesGrid")
    .Columns(columns =>
    {
        columns.ForeignKey(e => e.ProcedureCode, (System.Collections.IEnumerable)ViewBag.Procedures, "Code", "Name")
            .Width(250).Title("Процедура").HtmlAttributes(new { @class = "k-group-cell k-header" }).Locked(true);
        var roles = (IEnumerable<TD.CTS.Data.Entities.Role>)ViewBag.Roles;
        foreach (var role in roles)
        {
            columns.Template(e => { })
                .ClientTemplate("#= SelectedRole('" + role.Code + "', data) #")
                .Title(role.Name)
                .HeaderTemplate("<span class='rotate k-link'>" + role.Name + "</div>")
                .HtmlAttributes(new { @class = "td-role-cell", style = "text-align:center;" })
                .Width(80);

        }
        columns.Template(e => { }).ClientTemplate(" ").Width("100%").HtmlAttributes(new { @class = "k-group-cell" });
    })
    .ToolBar(toolbar =>
    {
        toolbar.Template(@<text>
            <div>
                <label style="display: inline-block;padding: 3px 5px 5px 5px;">Исследовательский центр:</label>
                @(Html.Kendo().DropDownList()
                    .HtmlAttributes(new { style="margin-bottom: 2px;" })
                    .Name("TrialCenterId")
                    .BindTo((System.Collections.IEnumerable)ViewBag.TrialCenters)
                    .DataTextField("Number")
                    .DataValueField("Id")
                )
                @(Html.Kendo().Button()
                    .Name("DefaultRolesButton")
                    .HtmlAttributes( new { @class = "k-primary" } )
                    .Content("Роли по умолчанию")
                    .Events(events => events.Click("DefaultRolesLoad"))
                )
            </div>
        </text>);
    })
    .DataSource(dataSource => dataSource
       .Ajax()
       .PageSize(50)
       .Model(model =>
       {
           model.Id(e => e.Id);
       })
       .Read(read => read.Action("GetTrialCenterProcedureRoles", "Trials").Data("GetParameters"))
       .Events(events => events.Error("kendo_grid_error_handler"))
    )
    .Scrollable(scroll => scroll.Height("auto"))
)

<script>
    $(document).ready(function () {
        kendo_grid_init($("#ProcedureRolesGrid"));
    });

    $("#ProcedureRolesGrid").on("click", ".td-role-cell", function () {
        Update($(this));
    });

    function GetParameters() {
        return {
            TrialCode: $("#Code").val(),
            TrialVersion: $("#Version").data("kendoDropDownList").value(),
            TrialCenterId: $("#TrialCenterId").data("kendoDropDownList").value()
        };
    }

    function SelectedRole(roleCode, data) {
        var index = GetRoleIndex(roleCode, data.Roles);
        var html = "<input type=\"hidden\" value=\"" + roleCode + "\" />";
        if (index !== -1)
            return html + "<span dataId=\"" + data.Roles[index].Id + "\" class=\"k-icon k-i-tick\"></span>";

        return html;
    }

    function GetRoleIndex(roleCode, roles) {
        if (!roles)
            return -1;
        for (var i = 0, len = roles.length; i < len; i++) {
            if (roles[i].RoleCode === roleCode)
                return i;
        }
        return -1;
    }

    function Update(cell) {
        var span = cell.find("span");
        var row = cell.closest("tr");
        var grid = $("#ProcedureRolesGrid").data("kendoGrid");
        var rowData = grid.dataItem(row);

        var data;
        var url;
        var roleExists = span.length > 0;
        if (roleExists) {
            data = { Id: span.attr("dataId") };
            url = "@Url.Action("DeleteTrialCenterProcedureRole", "Trials")";
        } else {
            data = {
                TrialCenterId: $("#TrialCenterId").data("kendoDropDownList").value(),
                ProcedureCode: rowData.ProcedureCode,
                TrialCode: rowData.TrialCode,
                TrialVersion: rowData.TrialVersion,
                RoleCode: cell.find("input").val()
            };
            url = "@Url.Action("AddTrialCenterProcedureRole", "Trials")";
        };

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            async: false,
            success: function (trialRole) {
                if (roleExists) {
                    var index = GetRoleIndex(cell.find("input").val(), rowData.Roles);
                    rowData.Roles.splice(index, 1);
                } else {
                    rowData.Roles.push(trialRole);
                }
                grid.dataSource.pushUpdate(rowData);

                var saveNotification = $("#SaveNotification").data("kendoNotification");
                saveNotification.show("Сохранено", "success");
            },
            error: function (error) {
                AjaxError(error);
            }
        });
    }

    function DefaultRolesLoad() {
        $.ajax({
            type: "POST",
            url: "@Url.Action("LoadProcedureDefaultRoles", "Trials")",
            data: GetTrialCode(),
            async: false,
            success: function () {
                var grid = $("#ProcedureRolesGrid").data("kendoGrid");
                grid.dataSource.read();
            },
            error: function (error) {
                AjaxError(error);
            }
        });
    }
</script>

<style>
    .rotate {
        padding-bottom: 100px !important;
        width: 150px;
        overflow: visible !important;
        white-space: normal !important;
        word-wrap:break-word;
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
        -ms-transform: rotate(-90deg);
        -o-transform: rotate(-90deg);
        transform: rotate(-90deg);
    }

    #ProcedureRolesGrid .k-grid-header .k-header {
      height: 150px;
      text-align: center;
    }

    #ProcedureRolesGrid tr td {
        border-width: 0 0 1px 1px;
    }
</style >